package add_two_numers

import(
)

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
type ListNode struct{
	Val int
	Next *ListNode
}

func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
	tmp1 := l1
	tmp2 := l2
	carry := 0
	result := &ListNode{}
	cur := result
	for tmp1 != nil && tmp2 != nil {
		sum := tmp1.Val + tmp2.Val
		sum += carry
		carry = 0

		if sum >= 10 {
			carry = 1
			sum -= 10
		}
		cur.Next = &ListNode{
			Val: sum,
		}
		cur = cur.Next
		tmp1 = tmp1.Next
		tmp2 = tmp2.Next
	}
	for tmp1 != nil {
		sum := tmp1.Val + carry
		carry = 0
		if sum >= 10 {
			carry = 1
			sum -= 10
		}
		cur.Next = &ListNode{
			Val: sum,
		}
		cur = cur.Next
		tmp1 = tmp1.Next
	}

	for tmp2 != nil {
		sum := tmp2.Val + carry
		carry = 0
		if sum >= 10 {
			carry = 1
			sum -= 10
		}
		cur.Next = &ListNode{
			Val: sum,
		}
		tmp2 = tmp2.Next
		cur = cur.Next
	}
	
	if carry > 0 {
        cur.Next = &ListNode{
            Val:1,
        }
	}
	
	result = result.Next
	return result
}

func makeList(nums []int) *ListNode {
	list := &ListNode{}
	cur := list 
	for _, v := range nums {
		cur.Next = &ListNode{
			Val: v,
		}
		cur = cur.Next
	}
	list = list.Next
	return list
}